from flask import Blueprint, request, jsonify, session, render_template
from models.User import User
from models.Company import Company
from models.Job import Job
from models.Application import Application
from models.Applicant import Applicant
from models import db

company_bp = Blueprint('company', __name__)


@company_bp.route('/companies')
def get_company_info():
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '未登录'}), 401

    user = User.query.get(user_id)
    company = Company.query.filter_by(user_id=user_id).first()

    if not user or not company:
        return jsonify({'success': False, 'message': '企业不存在'}), 404

    return jsonify({
        'success': True,
        'company': {
            'company_name': company.company_name,
            'industry': company.industry,
            'address': company.address,
            'scale': company.scale,
            'website': company.website,
            'contact_phone': company.contact_phone,
        }
    })


@company_bp.route('/companies/update', methods=['POST'])
def update_company_info():
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '未登录'}), 401

    data = request.get_json()
    user = User.query.get(user_id)
    company = Company.query.filter_by(user_id=user_id).first()

    if not user or not company:
        return jsonify({'success': False, 'message': '企业不存在'}), 404

    company.company_name = data.get('company_name', company.company_name)
    company.industry = data.get('industry', company.industry)
    company.address = data.get('address', company.address)
    company.scale = data.get('scale', company.scale)
    company.website = data.get('website', company.website)
    company.contact_phone = data.get('contact_phone', company.contact_phone)
    if data.get('password'):
        user.password = data['password']  # 更新密码

    db.session.commit()

    return jsonify({
        'success': True,
        'company': {
            'company_name': company.company_name,
            'industry': company.industry,
            'address': company.address,
            'scale': company.scale,
            'website': company.website,
            'contact_phone': company.contact_phone,
        }
    })

@company_bp.route('/company/recent_candidates', methods=['GET'])
def get_recent_candidates():
    """获取公司最近的候选人数据"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '未登录'}), 401

    try:
        # 获取当前公司信息
        company = Company.query.filter_by(user_id=user_id).first()
        if not company:
            return jsonify({'success': False, 'message': '企业不存在'}), 404

        # 查询该公司所有职位的申请
        # 关联查询以获取所需的所有数据
        recent_applications = (
            db.session.query(
                Application.application_id,
                Application.status,
                Application.ai_evaluation_score,
                Application.apply_time,
                Applicant.full_name,
                Job.title.label('job_title')
            )
            .join(Job, Application.job_id == Job.job_id)
            .join(Applicant, Application.applicant_id == Applicant.applicant_id)
            .filter(Job.company_id == company.company_id)
            .order_by(Application.apply_time.desc())
            .limit(10)  # 获取最近的10条数据
            .all()
        )

        # 格式化结果
        candidates = []
        for app in recent_applications:
            candidates.append({
                'application_id': app.application_id,
                'full_name': app.full_name,
                'job_title': app.job_title,
                'status': app.status,
                'ai_evaluation_score': app.ai_evaluation_score,
                'apply_time': app.apply_time.strftime('%Y-%m-%d %H:%M:%S')
            })

        # 即使没有候选人数据，也返回成功状态码和空数组
        return jsonify({
            'success': True,
            'candidates': candidates
        }), 200  # 显式指定200状态码

    except Exception as e:
        print(f"Error retrieving recent candidates: {e}")
        return jsonify({'success': False, 'message': f'获取候选人数据失败: {str(e)}'}), 500

@company_bp.route('/application/<int:application_id>', methods=['GET'])
def company_view_application(application_id):
    """公司查看某个应用详情"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '未登录'}), 401

    try:
        # 获取当前公司信息
        company = Company.query.filter_by(user_id=user_id).first()
        if not company:
            return jsonify({'success': False, 'message': '企业不存在'}), 404
            
        # 获取应用详情
        application = Application.query.get(application_id)
        if not application:
            return jsonify({'success': False, 'message': '申请不存在'}), 404
            
        # 获取职位信息，并确认该职位属于当前公司
        job = Job.query.get(application.job_id)
        if not job or job.company_id != company.company_id:
            return jsonify({'success': False, 'message': '无权访问此申请'}), 403
            
        # 获取申请人信息
        applicant = Applicant.query.get(application.applicant_id)
        if not applicant:
            return jsonify({'success': False, 'message': '申请人信息不存在'}), 404
            
        # 组装详细信息
        application_details = {
            'application_id': application.application_id,
            'applicant': {
                'id': applicant.applicant_id,
                'name': applicant.full_name,
                'phone': applicant.phone,
                'gender': applicant.gender,
                'education_level': applicant.education_level,
                'work_years': applicant.work_years,
                'expected_position': applicant.expected_position,
                'expected_salary': applicant.expected_salary
            },
            'job': {
                'id': job.job_id,
                'title': job.title,
                'job_type': job.job_type,
                'min_salary': job.min_salary,
                'max_salary': job.max_salary,
                'location': job.location
            },
            'status': application.status,
            'apply_time': application.apply_time.strftime('%Y-%m-%d %H:%M:%S'),
            'ai_evaluation_score': application.ai_evaluation_score,
            'feedback': application.feedback
        }
            
        # 渲染模板
        return render_template('company/application_detail.html', 
                             application=application_details, 
                             company=company)
            
    except Exception as e:
        print(f"Error retrieving application details: {e}")
        return jsonify({'success': False, 'message': f'获取申请详情失败: {str(e)}'}), 500

@company_bp.route('/save_feedback/<int:application_id>', methods=['POST'])
def save_feedback(application_id):
    """保存企业对申请的反馈"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '未登录'}), 401

    try:
        # 获取当前公司信息
        company = Company.query.filter_by(user_id=user_id).first()
        if not company:
            return jsonify({'success': False, 'message': '企业不存在'}), 404
            
        # 获取应用详情
        application = Application.query.get(application_id)
        if not application:
            return jsonify({'success': False, 'message': '申请不存在'}), 404
            
        # 获取职位信息，并确认该职位属于当前公司
        job = Job.query.get(application.job_id)
        if not job or job.company_id != company.company_id:
            return jsonify({'success': False, 'message': '无权访问此申请'}), 403
        
        # 获取请求数据    
        data = request.get_json()
        feedback = data.get('feedback')
        
        # 更新反馈
        application.feedback = feedback
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '反馈已保存'
        })
        
    except Exception as e:
        print(f"Error saving feedback: {e}")
        return jsonify({'success': False, 'message': f'保存反馈失败: {str(e)}'}), 500
